package com.base.http;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.base.control.ActivityStack;
import com.base.control.ContextControl;
import com.base.control.MActivitySupport;
import com.base.control.RequestCallback;
import com.base.model.Bean2Json;
import com.base.util.ConstantResource;
import com.base.util.Helper;
import com.base.util.MLog;
import com.base.util.StringUtil;
import com.base.view.dialog.LoadingDialogUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;


public class MJsonResponseHandler extends JsonHttpResponseHandler {
	private Context context;
	private int errorCode;
	private String errorMsg;
	private Bean2Json<?> b2jData;
	private RequestCallback controller;
	private String methodName;
    private boolean isShowToast;
    private static LoadingDialogUtil dialogUtil = new LoadingDialogUtil();
//    private LoadingDialog loadingDialog;
	
	public MJsonResponseHandler(MActivitySupport context, RequestCallback controller, Bean2Json<?> b2jData, String methodName, boolean isShowToast) {
		super();
		this.context = context;
		this.b2jData = b2jData;
		this.controller = controller;
		this.methodName = methodName;
        this.isShowToast = isShowToast;
        if(isShowToast) {
            dialogUtil.showDialog(context);
//            this.loadingDialog = new LoadingDialog(context);
//            loadingDialog.show();
        }
	}
	
	public void json2Info(JSONObject response) throws Exception {
		this.setErrorCode(response.getInt("errorCode"));
		this.setErrorMsg(response.getString("errorMsg"));
	}

	@Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        if(isShowToast)
            dialogUtil.dismissDialog();
        // If the response is JSONObject instead of expected JSONArray
		try {
			json2Info(response);
			if(errorCode != 0 && !TextUtils.isEmpty(errorMsg)) {
                if(isShowToast) {
                    Helper.toast(getContext(), errorMsg);
                }
                if(errorMsg.contains("登录验证失败")) { //跳转至登录界面
                    if(!isShowToast) {
                        Helper.toast(getContext(), errorMsg);
                    }
                    if(!ActivityStack.getScreenManager().currentActivity().getClass().equals(ConstantResource.LOGIN_ACTIVITY_CLASS)) {
                        Bundle data = new Bundle();
                        data.putInt(ConstantResource.LOGIN_VERIFY_ERROR_KEY, 1);
                        ContextControl.startContext(context, ConstantResource.LOGIN_ACTIVITY_CLASS, data);
                    }
                } else {
                    //回调错误信息处理
                    controller.onRequestError(errorCode, errorMsg);
                }
            } else if(errorCode == 0) {
				//取得data参数JSONObject
				b2jData.setResponseData(response);
				//调用回调函数
                if(!StringUtil.isEmpty(methodName))
				    controller.getClass().getMethod(methodName, Bean2Json.class).invoke(controller, b2jData);
                else {
                    controller.onRequestSuccess(b2jData);
                }
			}
		} catch (Exception e) {
            if(isShowToast)
			    Helper.toast(getContext(), ConstantResource.INTERFACE_ERROR);
            e.printStackTrace();
			MLog.d(controller.getClass().getSimpleName() + "" + e.getClass().getName());
            MLog.d(response);
 		}

    }
    
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
        if(isShowToast)
            dialogUtil.dismissDialog();
        // Pull out the first event on the public timeline
		try {
		} catch (Exception e) {
            if(isShowToast)
			    Helper.toast(getContext(), ConstantResource.INTERFACE_ERROR);
			MLog.d(e.getMessage());
		}
    }
    
    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
        if(isShowToast)
            dialogUtil.dismissDialog();
        if(isShowToast)
    	    Toast.makeText(getContext(), ConstantResource.NET_ERROR, Toast.LENGTH_SHORT).show();
        controller.onRequestError(0, "");
    	try {
			onFailureHandle();
		} catch (Exception e) {
            if(isShowToast)
			    Helper.toast(getContext(), ConstantResource.INTERFACE_ERROR);
			MLog.d(e.getMessage());
		}
    }

    public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	
	public void onFailureHandle() throws Exception {
		
	}

	public int getErrorCode() {
		return errorCode;
	}

	public void setErrorCode(int errorCode) {
		this.errorCode = errorCode;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public Bean2Json<?> getB2jData() {
		return b2jData;
	}

	public void setB2jData(Bean2Json<?> b2jData) {
		this.b2jData = b2jData;
	}
	
	
}
